﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyClassServer.Net;

namespace EasyClassServer.Application.UpdateUserInfo
{
    class UpdateUserInfo : IApplication
    {
        public string Name => "updateinfo";

        public HttpResponseArgs Handle(HttpArgs args)
        {
            UpdateUserInfoModel model = new UpdateUserInfoModel();
            var sex = args.GetPostValue()["sex"];
            var school = args.GetPostValue()["school"];
            var subject = args.GetPostValue()["subject"];
            var _class = args.GetPostValue()["class"];
            var token = args.GetPostValue()["token"];
            var email = args.GetPostValue()["email"];
            var correct_token = Data.CacheManager.GetCache(email.ToString());
            if (correct_token == null || correct_token.ToString() != token.ToString())
            {
                return new HttpResponseArgs
                {
                    Code = HttpCode.Error,
                    Message = "Token验证失败",
                    Data = null
                };
            }
            if (!model.Find("email", email.ToString()))
            {
                return new HttpResponseArgs
                {
                    Code = HttpCode.Error,
                    Message = "用户不存在",
                    Data = null
                };
            }
            var info = new Dictionary<string, object>();
            if (sex != null) info.Add("sex", sex.ToString());
            if (school != null) info.Add("school", school.ToString());
            if (subject != null) info.Add("subject", subject.ToString());
            if (_class != null) info.Add("class", _class.ToString());
            try
            {
                model.Update(new Dictionary<string, object> { { "email", email } }, info);
            }
            catch(Exception e)
            {
                return new HttpResponseArgs
                {
                    Code = HttpCode.Error,
                    Message = e.Message,
                    Data = null
                };
            }
            return new HttpResponseArgs
            {
                Code = HttpCode.Accept,
                Message = "用户信息已更新",
                Data = null
            };
        }
    }
}
